package gov.nbcs.govp.common.ui;

import com.foundercy.pf.control.Control;
import com.foundercy.pf.control.ControlException;
import com.foundercy.pf.control.DataField;
import com.foundercy.pf.control.FCheckBox;
import com.foundercy.pf.control.FDoubleDecimalField;
import com.foundercy.pf.control.FDoubleTimeChooser;
import com.foundercy.pf.control.dto.FDoubleDecimalDTO;
import com.foundercy.pf.control.dto.FDoubleTimeDTO;
import com.foundercy.pf.dictionary.control.FAssistComboBox;
import com.foundercy.pf.dictionary.control.FCard;
import com.foundercy.pf.dictionary.control.FTableAssistInput;
import com.foundercy.pf.dictionary.control.FTreeAssistInput;
import com.foundercy.pf.gl.dao.ConditionObj;
import com.foundercy.pf.gl.interfaces.IVoucherService;
import com.foundercy.pf.gl.viewer.FViewTools;
import com.foundercy.pf.util.BeanFactoryUtil;
import com.foundercy.pf.util.Global;
import com.foundercy.pf.util.UtilCache;
import com.foundercy.pf.util.XMLData;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.BeanFactory;

public class FQueryPanel extends FCard {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String userId = (String) Global.clientContext
			.getAttribute("user_id");

	private String moduleId = (String) Global.clientContext
			.getAttribute("module_id");

	private String uiid = "";

	private String xml = null;

	private final String DATE_FORMAT = "yyyy-MM-dd";

	public String getCondition() throws Exception {
		return getCondition(null);
	}

	public String getCondition(String tableAlias) throws Exception {
		StringBuffer return_str = new StringBuffer();

		if (getData() != null) {
			Map data = getData();
			if (getXml() != null) {
				Document doc = DocumentHelper.parseText(getXml());
				Element root = doc.getRootElement();
				List children = root.elements();
				for (int i = 0; (children != null) && (i < children.size()); i++) {
					Element child = (Element) children.get(i);
					String id = child.attributeValue("id");
					String source = child.attributeValue("source");

					if ((data.get(id) == null) || (data.get(id).equals(""))) {
						continue;
					}

					String relationSignCode = "0";
					if (child.attributeValue("query_relation_sign") != null) {
						relationSignCode = child
								.attributeValue("query_relation_sign");
					}

					if ((data.get(id) instanceof List)) {
						String relationSign = getRelationSignByCode(relationSignCode);

						String chr_code = id.toLowerCase().replaceAll("_id",
								"_code");

						Iterator tmp = ((List) data.get(id)).iterator();
						StringBuffer bf = new StringBuffer();
						while (tmp.hasNext()) {
							XMLData tmp_xmldata = (XMLData) tmp.next();
							String tmp_code = (String) tmp_xmldata
									.get(chr_code);
							String tmp_id = (String) tmp_xmldata.get(id);
							if ((source != null)
									&& (!source.equals(""))
									&& (("like".equalsIgnoreCase(relationSign)) || ("not like"
											.equalsIgnoreCase(relationSign)))
									&& (tmp_code != null)
									&& (!"".equals(tmp_code))) {
								bf
										.append(tableAlias + "." + chr_code
												+ " " + relationSign + " '"
												+ tmp_code + "%'");
							} else {
								bf.append(tableAlias + "." + id + " "
										+ relationSign + " '" + tmp_id + "'");
							}

							if (tmp.hasNext()) {
								bf.append(" or ");
							}
						}
						if (bf.length() > 0) {
							return_str.append(" and (");
							return_str.append(bf);
							return_str.append(")");
						}
					} else {
						Control cntr = getSubControl(id);

						if (((cntr instanceof FTreeAssistInput))
								|| ((cntr instanceof FTableAssistInput))
								|| ((cntr instanceof FAssistComboBox))) {
							String relationSign = getRelationSignByCode(relationSignCode);

							String chr_code = id.toLowerCase().replaceAll(
									"_id", "_code");

							String tmp_code = (String) data.get(chr_code);
							String tmp_id = (String) data.get(id);
							if ((source != null)
									&& (!source.equals(""))
									&& (("like".equalsIgnoreCase(relationSign)) || ("not like"
											.equalsIgnoreCase(relationSign)))
									&& (tmp_code != null)
									&& (!"".equals(tmp_code))) {
								return_str.append(" and " + tableAlias + "."
										+ chr_code + " " + relationSign + " '"
										+ tmp_code + "%'");
							} else {
								return_str.append(" and " + tableAlias + "."
										+ id + " " + relationSign + " '"
										+ tmp_id + "'");
							}

						} else if (((cntr instanceof FDoubleTimeChooser))
								|| ((cntr instanceof FDoubleDecimalField))) {
							String relationSign = getRelationSignByCode(relationSignCode);

							String chr_code = id.toLowerCase();
							Object tmp_object = data.get(chr_code);

							String tmp_id_low = "";
							String tmp_id_hight = "";

							if ((cntr instanceof FDoubleTimeChooser)) {
								FDoubleTimeDTO tmp_dto = (FDoubleTimeDTO) data
										.get(id);

								tmp_id_low = new SimpleDateFormat("yyyy-MM-dd")
										.format(tmp_dto.getStartDate());

								tmp_id_hight = new SimpleDateFormat(
										"yyyy-MM-dd").format(tmp_dto
										.getEndDate());
							}

							if ((cntr instanceof FDoubleDecimalField)) {
								FDoubleDecimalDTO tmp_dto = (FDoubleDecimalDTO) data
										.get(id);

								if (tmp_dto.getStartDecimal() != null) {
									tmp_id_low = tmp_dto.getStartDecimal()
											.toString();
								}
								if (tmp_dto.getEndDecimal() != null) {
									tmp_id_hight = tmp_dto.getEndDecimal()
											.toString();
								}

							}

							if (("between".equalsIgnoreCase(relationSign))
									&& ((cntr instanceof FDoubleDecimalField))
									&& (tmp_object != null)) {
								if (!"".equalsIgnoreCase(tmp_id_low)) {
									return_str.append(" and " + tableAlias
											+ "." + chr_code + " > "
											+ tmp_id_low);
								}

								if (!"".equalsIgnoreCase(tmp_id_hight)) {
									return_str.append(" and " + tableAlias
											+ "." + chr_code + " " + "< "
											+ tmp_id_hight);
								}

							} else if (("between"
									.equalsIgnoreCase(relationSign))
									&& ((cntr instanceof FDoubleTimeChooser))
									&& (tmp_object != null)) {
								return_str.append(" and " + tableAlias + "."
										+ chr_code + " " + "< '" + tmp_id_hight
										+ "' and " + tableAlias + "."
										+ chr_code + " > '" + tmp_id_low + "'");
							} else if (((cntr instanceof FDoubleDecimalField))
									&& (tmp_object != null)) {
								if (!"".equalsIgnoreCase(tmp_id_low)) {
									return_str.append(" and " + tableAlias
											+ "." + chr_code + " >= "
											+ tmp_id_low);
								}

								if (!"".equalsIgnoreCase(tmp_id_hight)) {
									return_str.append(" and " + tableAlias
											+ "." + chr_code + " " + "<= "
											+ tmp_id_hight);
								}

							} else if (((cntr instanceof FDoubleTimeChooser))
									&& (tmp_object != null)) {
								return_str.append(" and " + tableAlias + "."
										+ chr_code + " " + "<= '"
										+ tmp_id_hight + "' and " + tableAlias
										+ "." + chr_code + " >= '" + tmp_id_low
										+ "'");
							}

						} else {
							String relationSign = getRelationSignByCode(relationSignCode);

							return_str.append(" and ").append(tableAlias)
									.append(".").append(id).append(" ").append(
											relationSign).append(" '");

							String insertPercentSigh = child
									.attributeValue("insertPercentSigh");

							if (("true".equalsIgnoreCase(insertPercentSigh))
									&& (("like".equalsIgnoreCase(relationSign)) || ("not like"
											.equalsIgnoreCase(relationSign)))) {
								return_str.append("%");
							}

							return_str.append(data.get(id));
							if (("like".equalsIgnoreCase(relationSign))
									|| ("not like"
											.equalsIgnoreCase(relationSign))) {
								return_str.append("%");
							}
							return_str.append("'");
						}
					}
				}

			}

			String back = return_str.toString();
			if (tableAlias == null) {
				back = back.replaceAll("null.", "");
			}
			return back;
		}
		return null;
	}

	public XMLData getData() {
		XMLData xmlData = new XMLData();
		if ((this.isKeepOriginalDataStructure) && (this.xmlData != null)) {
			xmlData.putAll(this.xmlData);
		}
		List subCtrls = getSubControls();
		for (int i = 0; (subCtrls != null) && (i < subCtrls.size()); i++) {
			Control cntr = (Control) subCtrls.get(i);
			if ((cntr instanceof DataField)) {
				Object value = ((DataField) cntr).getValue();
				xmlData.remove(cntr.getId());
				if ((cntr instanceof FCheckBox)) {
					if ((value instanceof Boolean)) {
						if (((Boolean) value).booleanValue())
							xmlData.put(cntr.getId(), "1");
						if (!((Boolean) value).booleanValue()) {
							xmlData.put(cntr.getId(), "0");
						}

					}

				} else if ((cntr instanceof FDoubleDecimalField)) {
					value = ((FDoubleDecimalField) cntr).getDoubleValue();
					xmlData.put(cntr.getId(), value);
				} else {
					xmlData.put(cntr.getId(), value);
				}

			}

			if ((cntr instanceof FTreeAssistInput)) {
				if (!((FTreeAssistInput) cntr).getIsCheck()) {
					XMLData value = ((FTreeAssistInput) cntr).getSelectedData();
					String chr_code = cntr.getId().toLowerCase().replaceAll(
							"_id", "_code");

					String chr_name = cntr.getId().toLowerCase().replaceAll(
							"_id", "_name");

					if ((value != null) && (value.get("chr_code") != null)) {
						xmlData.put(chr_code, value.get("chr_code").toString());
					}
					if ((value != null) && (value.get("chr_name") != null))
						xmlData.put(chr_name, value.get("chr_name").toString());
				} else {
					String id = cntr.getId().toLowerCase();
					String code = cntr.getId().toLowerCase().replaceAll("_id",
							"_code");

					String name = cntr.getId().toLowerCase().replaceAll("_id",
							"_name");

					List value = ((FTreeAssistInput) cntr)
							.getAllSelectedDatas();

					List switch_vaule = new ArrayList();

					if (value != null) {
						Iterator itr = value.iterator();

						while (itr.hasNext()) {
							XMLData tmp = (XMLData) itr.next();
							String chr_id = (String) tmp.get("chr_id");
							String chr_code = (String) tmp.get("chr_code");
							String chr_name = (String) tmp.get("chr_name");
							tmp = null;
							tmp = new XMLData();
							tmp.put(id, chr_id);
							tmp.put(code, chr_code);
							tmp.put(name, chr_name);
							switch_vaule.add(tmp);
						}
					}
					xmlData.put(id, switch_vaule);
				}

			}

			if ((cntr instanceof FTableAssistInput)) {
				XMLData value = ((FTableAssistInput) cntr).getSelectedData();
				String chr_code = cntr.getId().toLowerCase().replaceAll("_id",
						"_code");

				String chr_name = cntr.getId().toLowerCase().replaceAll("_id",
						"_name");

				if ((value != null) && (value.get("chr_code") != null)) {
					xmlData.put(chr_code, value.get("chr_code").toString());
				}
				if ((value != null) && (value.get("chr_name") != null)) {
					xmlData.put(chr_name, value.get("chr_name").toString());
				}
			}

			if ((cntr instanceof FAssistComboBox)) {
				XMLData value = ((FAssistComboBox) cntr).getSelectedData();
				String chr_code = cntr.getId().toLowerCase().replaceAll("_id",
						"_code");

				String chr_name = cntr.getId().toLowerCase().replaceAll("_id",
						"_name");

				if ((value != null) && (value.get("chr_code") != null)) {
					xmlData.put(chr_code, value.get("chr_code").toString());
				}
				if ((value != null) && (value.get("chr_name") != null)) {
					xmlData.put(chr_name, value.get("chr_name").toString());
				}
			}

		}

		return xmlData;
	}

	public String getBalanceCondition(String billTypeCode) throws Exception {
		BeanFactory factory = BeanFactoryUtil
				.getBeanFactory("com/foundercy/pf/gl/interfaces/voucher.xml");

		IVoucherService voucher = (IVoucherService) factory
				.getBean("sys.voucherService");

		return voucher.getCondition(billTypeCode, getBalanceConditionObj());
	}

	public ConditionObj getBalanceConditionObj() {
		ConditionObj obj = new ConditionObj();
		Iterator it = getData().keySet().iterator();

		while (it.hasNext()) {
			String key = it.next().toString();
			if ((getData().get(key) instanceof FDoubleTimeDTO)) {
				FDoubleTimeDTO dto = (FDoubleTimeDTO) getData().get(key);
				obj.add("and", key, "<=", dto.getEndDate().toString());

				obj.add("and", key, ">=", dto.getStartDate().toString());
			} else if ((getData().get(key) instanceof FDoubleDecimalDTO)) {
				FDoubleDecimalDTO dto = (FDoubleDecimalDTO) getData().get(key);

				obj.add("and", key, "<=", dto.getEndDecimal().toString());

				obj.add("and", key, ">=", dto.getStartDecimal().toString());
			} else {
				String key_value = (String) getData().get(key);
				if ((key.indexOf("_id") != -1) && (key_value != null)
						&& (!key_value.equals(""))) {
					obj.add("and", key, "=", key_value);
				}
			}
		}

		return obj;
	}

	public void create(String uiid) throws ControlException {
		String xml = UtilCache.getUIXML(uiid);
		if ((xml != null) && (!xml.equals(""))) {
			FViewTools.loadControlByXmlStr(this, this.userId, this.moduleId,
					xml);
		} else {
			xml = FViewTools.loadControlByViewID(this, this.userId,
					this.moduleId, uiid);
			UtilCache.putUIXML(uiid, xml);
		}
		setUiid(uiid);
	}

	public void createByXml(String xml) throws ControlException {
		FViewTools.loadControlByXmlStr(this, this.userId, this.moduleId, xml);
	}

	public void createByFile(String file) throws ControlException {
		FViewTools.loadControlByFile(this, this.userId, this.moduleId, file);
	}

	public String getUiid() {
		return this.uiid;
	}

	public void setUiid(String uiid) {
		this.uiid = uiid;
	}

	public String getXml() {
		return this.xml;
	}

	public void setXml(String xml) {
		this.xml = xml;
	}

	public void clearFQueryPanelCache(String ui_id) {
		if ((UtilCache.uiMap != null) && (!UtilCache.uiMap.equals(""))) {
			ui_id = ui_id + Global.getSetYear();
			UtilCache.uiMap.remove(ui_id);
		}
	}

	private String getRelationSignByCode(String relationSignCode) {
		if ("0".equals(relationSignCode)) {
			return "=";
		}
		if ("1".equals(relationSignCode)) {
			return "!=";
		}
		if ("2".equals(relationSignCode)) {
			return ">";
		}
		if ("3".equals(relationSignCode)) {
			return ">=";
		}
		if ("4".equals(relationSignCode)) {
			return "<";
		}
		if ("5".equals(relationSignCode)) {
			return "<=";
		}
		if ("6".equals(relationSignCode)) {
			return "like";
		}
		if ("7".equals(relationSignCode)) {
			return "not like";
		}
		if ("8".equals(relationSignCode)) {
			return "between";
		}
		if ("9".equals(relationSignCode)) {
			return "betweenequal";
		}
		return "=";
	}

	public FTreeAssistInput getTreeAssistInput(String element) {
		FTreeAssistInput TreeInput = (FTreeAssistInput) this
				.getSubControl(element);
		return TreeInput;
	}

}